package com.fengye.rabbit.login.message;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 3:44 下午
 */
@Component
@Slf4j
public class MessageConfig {

    @Value("${login.message.queue.name:login-queue-name}")
    private String queueName;

    @Value("${login.message.exchange.name:login-exchange-name}")
    private String exchangeName;

    @Value("${login.message.route.name:login-route-name}")
    private String routeName;

    @Bean(name = "loginQueue")
    public Queue loginQueue() {
        return new Queue(queueName);
    }

    @Bean(name = "loginExchange")
    public TopicExchange loginExchange() {
        return new TopicExchange(exchangeName);
    }

    @Bean(name = "loginBinding")
    public Binding loginBinding(@Qualifier("loginQueue") Queue loginQueue, @Qualifier("loginExchange") TopicExchange loginExchange) {
        return BindingBuilder.bind(loginQueue).to(loginExchange).with(routeName);
    }

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;


    @Bean(name = "singleListenerContainer")
    public SimpleRabbitListenerContainerFactory listenerContainer() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(cachingConnectionFactory);
        // 设置消息在传输中的格式，在这里采用 JSON 格式进行传输
        factory.setMessageConverter(new Jackson2JsonMessageConverter());

        // 设置并发消费者示例的初始数量
        factory.setConcurrentConsumers(1);

        // 设置并发消费者示例的最大数量
        factory.setMaxConcurrentConsumers(1);

        // 设置并发消费者示例中每个示例拉取的数量
        factory.setPrefetchCount(1);
        return factory;
    }
}
